#include "workCmd.h"

int registerUser(int sockFd){
    char userName[100] = {0};
    char passwd[100] = {0};
    int check = 0;

    printf("Plz enter userName:");
    scanf("%s",userName);
    printf("Plz enter passwd:");
    scanf("%s",passwd);

    trainState_t trainState;
    bzero(&trainState,sizeof(trainState));
    trainState.state = REGISTER;
    strcpy(trainState.buf,userName);
    trainState.length = strlen(trainState.buf);
    send(sockFd,&trainState,
         sizeof(trainState.length) + sizeof(trainState.state)+ 
         sizeof(trainState.preLength) + trainState.length,MSG_NOSIGNAL);

    //接收盐值
    char cryptPasswd[50] = {0};
    char salt[SATL_LEN + 1] = {0};
    int cryptLength = 0;
    recvn(sockFd,&cryptLength,sizeof(cryptLength));
    recvn(sockFd,salt,cryptLength);

    //发送密文
    strncpy(cryptPasswd,crypt(passwd,salt),49);
    train_t train;
    bzero(&train,sizeof(train));
    train.length = strlen(cryptPasswd);
    strcpy(train.data,cryptPasswd);
    send(sockFd,&train,sizeof(train.length) + train.length,MSG_NOSIGNAL);

    //接收注册状态回执
    recvn(sockFd,&check,sizeof(check));
    return check;
}

int login(int sockFd,char *userName){
    char name[100] = {0};
    int check = 0;

    printf("Plz enter userName:");
    scanf("%s",name);

    trainState_t trainState;
    while(1){
        check = 0;
        bzero(&trainState,sizeof(trainState));
        //安全输入密码
        char *passwd = getpass("Plz enter your password:");
        trainState.state = LOGIN;
        strcpy(trainState.buf,name);
        trainState.length = strlen(trainState.buf);
        send(sockFd,&trainState,
             sizeof(trainState.length) + sizeof(trainState.state)+ 
             sizeof(trainState.preLength) + trainState.length,MSG_NOSIGNAL);

        //查看用户是否存在
        recvn(sockFd,&check,sizeof(check));
        if(check == 2){
            //未注册
            break;
        }
        //接收盐值
        char cryptPasswd[50] = {0};
        char salt[SATL_LEN + 1] = {0};
        int cryptLength = 0;
        recvn(sockFd,&cryptLength,sizeof(cryptLength));
        recvn(sockFd,salt,cryptLength);
        //发送密文
        strncpy(cryptPasswd,crypt(passwd,salt),49);
        printf("CryptPasswd = %s\n",cryptPasswd);
        train_t train;
        bzero(&train,sizeof(train));
        train.length = strlen(cryptPasswd);
        strcpy(train.data,cryptPasswd);
        send(sockFd,&train,sizeof(train.length) + train.length,MSG_NOSIGNAL);

        //接收验证结果
        recvn(sockFd,&check,sizeof(check));
        printf("check = %d\n",check);
        if(check == 0){
            //密码验证成功
            strcpy(name,userName);
            break;
        }else{
            printf("Passwd is wrong!\n");
        }
    }
    return check;
}



